from flask_restful import Resource, abort, marshal
from common import Common_Methd
from model import User, db


#: argsParse 参数解释
from flask_restful import reqparse

parser = reqparse.RequestParser()
parser.add_argument('user_name', required=True)
parser.add_argument('user_password', required=True)
parser.add_argument('user_nickname')
parser.add_argument('user_email', required=True)

#: fields 对象
from flask_restful import fields

resource_full_fields = {	
	'user_id': fields.Integer,
	'user_name': fields.String,
	'user_email': fields.String,
	'user_nickname': fields.String
}


class Demo(Resource):
	
	def get(self):
		return { 'content': 'Hello World' }

class Users(Resource):

	def get(self, userId=None):
		if userId is not None:
			data = User.query.filter_by(user_id=userId).first()		
			if (data is None):
				abort(410, msg="Not Found data", data=None, status=0)
			else:
				return Common_Methd.returnTrueJson(marshal(data, resource_full_fields))
	
	def delete(self, userId):
		deleteRow = User.query.filter_by(user_id=userId).delete()
		db.session.commit()
		if (deleteRow):
			return Common_Methd.returnTrueJson(None, "Delete successful")
		else:
			return Common_Methd.returnFalseJson(None, "Delete error")
	
	def put(self, userId):
		args = parser.parse_args()
		user_name = args['user_name']
		user_password = args['user_password']
		user_nickname = args['user_nickname']
		user_email = args['user_email']
		
		try:
			user = User.query.filter_by(user_id=userId).first()
			
			user.user_name = user_name
			user.user_password = user_password
			user.user_nickname = user_nickname
			user.user_email = user_email
			
			db.session.commit()
			userId = user.user_id
			data = User.query.filter_by(user_id=userId).first()
			
			return Common_Methd.returnTrueJson(marshal(data, resource_full_fields))
		except:
			db.session.rollback()
			db.session.flush()
			abort(409, msg="Modify errors", data=None, status=0)

	def post(self, userId):
		args = parser.parse_args()
		# id = args['userId']
		name = args['user_name']
		email = args['user_email']
		nick = args['user_nickname']
		password = args['user_password']
		try:
			new_user = User(user_id=userId, user_name=name, user_email=email, user_nickname=nick, user_password=password)
			db.session.add(new_user)
			db.session.commit()
			return Common_Methd.returnTrueJson(marshal(new_user, resource_full_fields))
		except:
			db.session.rollback()
			db.session.flush()
			return Common_Methd.returnFalseJson(None, 'Regist error')

			